package com.xiamo.socket;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;

/**
 * 
 *
 * @author Richard - rui.wu@bitmain.com
 * @since 2016年7月21日 
 *
 */
public class MinerSocketDemo {
	
	public static enum Command {
		/**
		 * 矿机MAC地址命令
		 */
		MAC("", 1 << 1),
		/**
		 * 矿机状态信息命令
		 */
		STATS("{\"command\":\"stats\"}", 1 << 2),
		/**
		 * 矿机汇总信息命令
		 */
		SUMMARY("{\"command\":\"summary\"}", 1 << 3),
		/**
		 * 矿机矿池配置信息命令
		 */
		POOLS("{\"command\":\"pools\"}", 1 << 4),
		/**
		 * 所有命令
		 */
		ALL("", 1 << 5);
		
		public int key;
		public String value;
		
		private Command(String value, int key) {
			this.value = value;
			this.key = key;
		}
	}
	public static void main(String[] args) {
		Socket socket = null;
		BufferedWriter writer = null;
		BufferedReader reader = null;
		StringBuilder response = new StringBuilder();
		String host ="192.168.20.23";
		int port = 4028;
		String cmd = Command.STATS.value;
		System.out.println(cmd);
		
		try {
			socket = new Socket();
			socket.setSoTimeout(20000);
			socket.connect(new InetSocketAddress(host,port));
			writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
			writer.write(cmd);
			writer.flush();
			
			reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			String line;
			while((line=reader.readLine())!=null){
				response.append(line);
			}
			System.out.println(response.toString());
			
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (reader != null) {
					reader.close();
				}
				if (writer != null) {
					writer.close();
				}
				if (socket != null) {
					socket.close();
				}
				
			} catch (Exception e2) {
			}
		}
	}
}
